import Foundation
import Combine

class IPInfoViewModel: ObservableObject {
    @Published var ipInfo: IPInfo?
    @Published var errorMessage: String?
    
    private var cancellables = Set<AnyCancellable>()
    
    init() {
        fetchIPInfo()
    }
    
    func fetchIPInfo() {
        guard let url = URL(string: "https://ipinfo.io/json") else {
            self.errorMessage = "Invalid URL"
            return
        }
        
        URLSession.shared.dataTaskPublisher(for: url)
            .map { $0.data }
            .decode(type: IPInfo.self, decoder: JSONDecoder())
            .receive(on: DispatchQueue.main)
            .sink(receiveCompletion: { completion in
                switch completion {
                case .finished:
                    break
                case .failure(let error):
                    self.errorMessage = "Error fetching data: \(error.localizedDescription)"
                }
            }, receiveValue: { ipInfo in
                self.ipInfo = ipInfo
            })
            .store(in: &self.cancellables)
    }
}


import Foundation

struct IPInfo: Codable {
    let ip: String
    let hostname: String
    let city: String
    let region: String
    let country: String
    let loc: String
    let org: String
    let postal: String
    let timezone: String
    let readme: String
}
